const $config = require('../nuxt.config.js')
const $axios =require('../lib/axios'); 
const timeago = require('../lib/timeago');
const $redis = require("../lib/redis"); // 你的redis配置文件路径

module.exports = function (Data) {
   
    //发布新帖子  
    Data.newTopic= async function (topic) {
        // topic._uid = $config.UID;
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                "Authorization": bearer,
             }
        }
        // https://community.nodebb.org/api/v3/topics/
        let url = $config.axios.baseURL+"api/v3/topics"
        let res = {};
        if(topic.tid){//修改帖子
            topic.pid = topic.mainPid;
            res = await Data.reply(topic);
            return res;
        }
        //发布 
        res = await  $axios.post(url,topic,headers);
        return res; 
	};


    //回复
    Data.reply= async function (post) {
        // post._uid = $config.UID;
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        // https://community.nodebb.org/api/v3/topics/{tid}
        // https://community.nodebb.org/api/v3/posts/{pid}
        let url = $config.axios.baseURL+"api/v3/topics/"+post.tid;
        let res = {};
        if(post.pid){//修改回复
            url = $config.axios.baseURL+"api/v3/posts/"+post.pid;
            return    await  $axios.put(url,post,headers);
        }
        // console.log("post reply:", post)
        //发布 
        return await $axios.post(url,post,headers);; 
	};

    // 获取一个topic
    Data.getTopic= async function (tid) {
       
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        // https://community.nodebb.org/api/v3/topics/{tid}
        let url = $config.axios.baseURL+"api/v3/topics/"+tid+"?_uid="+$config.UID;
        let res =  await $axios.get(url,headers);
        if(res.code>0){
            return res;
        }
        // console.log("res",res)
        let topic = res.data;
        if(topic.materials){
            topic.materials = JSON.parse(topic.materials)
        }
        if(topic.terrain_attribute){
            topic.terrain_attribute = JSON.parse(topic.terrain_attribute)
        }
        if(topic.elevation){
            topic.elevation = JSON.parse(topic.elevation)
        }
        if(topic.lifts){
            topic.lifts = JSON.parse(topic.lifts)
        }
        if(topic.important_dates){
            topic.important_dates = JSON.parse(topic.important_dates)
        }
        
        topic.timestamp = timeago(topic.timestamp );
        topic.lastposttime = timeago(topic.lastposttime );
        let tags =[];
        if(topic.tags){
            for (const k in topic.tags) {
                tags.push(topic.tags[k].value);
            }
        }
        topic.tag_values = tags;
        
        let user = await Data.getUser(topic.uid);
        if(res.code==0){
            topic.user = user.data;
        }
        let post = await Data.getPost(topic.mainPid);
        if(res.code==0){
            topic.post = post.data;
        }
        res.data = topic;
        return res;

	};


     // 获取一个Post
     Data.getPost= async function (pid) {
       
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        let url = $config.axios.baseURL+"api/v3/posts/"+pid+"?_uid="+$config.UID;
        let res =  await $axios.get(url,headers);
        let post = res.data;
        if(post.materials){
            post.materials = JSON.parse(post.materials)
        }
        res.data = post;
       return res;

	};
    // posts
    Data.getPostsBySlug= async function (slug) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        slug = encodeURI(slug);
        let url = $config.axios.baseURL+"api/topic/"+slug+"?_uid="+$config.UID;
        ////console.log("url:",url)
        let res =  await $axios.get(url,headers);
        if(res.code>0){
           return res;
        }
        let posts = res.data.posts;
        for (const k in posts) {
            if(posts[k].materials){
                posts[k].materials = JSON.parse(posts[k].materials)
            }
            posts[k].timestamp =  timeago(posts[k].timestamp );
            posts[k].lastposttime =  timeago(posts[k].lastposttime );
            posts[k].user.picture = Data.picture(posts[k].user.picture);
        }
        return {
            code:0,
            msg:'success',
            data:posts
        };
        // ////console.log("posts:",posts);
    }
    // getTopicsByTag
    Data.getTopicsByTag= async function (tag) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        // /api/tags/deer%20valley%20res
        // tag = encodeURIComponent(tag)
        let url = $config.axios.baseURL+"api/tags/"+tag+"?_uid="+$config.UID;
        ////console.log("url:",url)
        let res =  await $axios.get(url,headers);
        if(res.code>0){
           return res;
        }
        let topics = res.data.topics;
        for (const k in topics) {
            if(topics[k].materials){
               topics[k].materials = JSON.parse(topics[k].materials)
            }
            topics[k].timestamp = timeago(topics[k].timestamp );
            topics[k].lastposttime = timeago(topics[k].lastposttime);
            topics[k].user.picture = Data.picture(topics[k].user.picture);
        }
        return {
            code:0,
            msg:'success',
            data:topics
        };
        // ////console.log("posts:",posts);
    }

    // vote
    Data.vote= async function (pid,type="up",uid=0) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        let url = $config.axios.baseURL+"api/v3/posts/"+pid+"/vote?_uid="+uid;
        let res ={}
        if(type=="up"){
             res =  await $axios.put(url,{delta:1,"_uid":uid},headers);
        }else{
            //  res =  await $axios.delete(url,headers);
            res =  await $axios.put(url,{delta:-1,"_uid":uid},headers);
        }
        return res;
    }

    // bookmark
    Data.bookmark= async function (pid,type="add",uid=0) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        let url = $config.axios.baseURL+"api/v3/posts/"+pid+"/bookmark?_uid="+uid;
        let res ={}
        if(type=="add"){
             res =  await $axios.put(url,{"_uid":uid},headers);
        }else{
             res =  await $axios.delete(url,headers);
        }
        return res;
    }

    // votehttps://community.nodebb.org/api/v3/flags/
    Data.flag= async function (post,uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        let url = $config.axios.baseURL+"api/v3/flags";
        post._uid =uid
        let res =  await $axios.post(url,post,headers);
        return res;
    }
    // rateSkiResort
    Data.rateSkiResort= async function (skiResortId=0,rates={}) {
        // all_mountain_terrain: 5
        // apres_ski: 4
        // beginner: 5
        // expert: 4
        // family_friend: 5
        // intermediate: 4
        // overall_rating: 5
        // overall_value: 4
        // terrain_park: 4
       let topic = await $redis.hgetall("topic:"+skiResortId)
    //    ////console.log("topic:",topic)
       if(!(topic) || !topic.tid){
           return {code:1,msg:'topic not found!'};
       }
       
       let keys =["all_mountain_terrain","apres_ski","beginner","expert","family_friend","intermediate","overall_rating",'overall_value',"terrain_park"];
       let update ={};
          //    总评分人数
       update["rate_count"] = topic["rate_count"]?(Number(topic["rate_count"])+1):1;
       let tags =[];
       for (var key of keys) {
          var _count = topic[key+"_count"] ? Number(topic[key+"_count"]) : 0;
          update[key+"_count"] =(_count)+1;
          if(!rates[key]){
            rates[key] =3;
          }
          if(!topic[key]){
            topic[key] =0;
          }
        //   ////console.log("key:",key,rates[key],topic[key],update[key+"_count"])
          update[key] =parseInt(   (Number(rates[key])+Number(topic[key])*_count)/update[key+"_count"]);
        //   console.log("key:",key,"update[key]:",update[key])
          if(update[key]  > 3 && update["rate_count"] >15 ){
             let tag  =  Data.replaceAll("_"," ",key)
             tags.push(tag);
          }
        }
 
    //    按星星统计 评分人数 
       update["overall_rating_"+rates['overall_rating']] = topic["overall_rating_"+rates['overall_rating']]?(Number(topic["overall_rating_"+rates['overall_rating']])+1):1
    //    百分比
       update["overall_rating_"+rates['overall_rating']+"_progress"] =  parseInt(update["overall_rating_"+rates['overall_rating']]/update["rate_count"])*100;
       ////console.log("topic",topic,"update:",update);

       let i = await $redis.hmset("topic:"+skiResortId, update)
       if(tags.length>0){
           let res =  await Data.addTags(skiResortId,tags);
           console.log("addTags:",res);
       }
       if(i){
          Data.indexTopic(skiResortId);
       }
       return {code:0,msg:i} ;
    }
//    adds tags to a topic
// {
//     "tags": [
//     "test",
//     "foobar"
//     ]
//     }
 Data.addTags= async function (tid,tags) {
    let bearer = "Bearer "+$config.apiAuthorization;
    let headers = {
        headers : {
            'Authorization': bearer,
         }
    }
    
    let data = {
        "tags":  tags,
        "_uid":$config.UID
    };
        // https://community.nodebb.org/api/v3/topics/{tid}/tags
    let url = $config.axios.baseURL+"api/v3/topics/"+tid+"/tags";
    let res =  await $axios.put(url,data,headers);
    return res;
}
    // 删除帖子
    Data.delTopic= async function (tid,uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        let topic = await Data.getTopic(tid);
        if(topic.code>0){
            return topic;
        }
       let isAdministrators =  await Data.isAdministrators(7);

        if(topic.data.uid!=uid && isAdministrators===false ){
            return {
                code:2,
                msg:'Operation without permission!',
            }
        }
        // https://community.nodebb.org/api/v3/topics/{tid}/state
        let url = $config.axios.baseURL+"api/v3/topics/"+tid+"/state?_uid="+$config.UID;
        console.log("url:",url);
        let res =  await $axios.delete(url,headers);
        return res;
    }


    // 删除帖子
    // https://community.nodebb.org/api/v3/posts/{pid}
    Data.delPost= async function (pid,uid) {
        let bearer = "Bearer "+$config.apiAuthorization;
        let headers = {
            headers : {
                'Authorization': bearer,
             }
        }
        let post = await Data.getPost(pid);
        if(post.code>0 || !post.data.pid){
            return post;
        }
       let isAdministrators =  await Data.isAdministrators(7);

        if(post.data.uid!=uid && isAdministrators===false ){
            console.log("post.data.uid:",post.data.uid,"uid:",uid)
            return {
                code:2,
                msg:'Operation without permission!',
            }
        }
        // https://community.nodebb.org/api/v3/posts/{tid}/state
        let url = $config.axios.baseURL+"api/v3/posts/"+pid+"?_uid="+$config.UID;
        // console.log("url:",url);
        let res =  await $axios.delete(url,headers);
        return res;
    }

    
// 用户首页上的文章 
    Data.userIndexTopic=async function (uid,page=1) {
       let start = (page-1)*5;
       let categorys =  await Data.getUserCategory(uid,0,5);
       let list =[];
       var q={};
       for (const i in categorys) {
           var category = categorys[i]
           q={
                userCategoryId:category.score,
                type:'topic',
                size:4,
                from:0
           }
           var res = await Data.getDocsBykeywords(q);
           if(res.code==0){
                category.list = res.data.list
                list.push(category);
           }  
       }
    //  
        var q={
            userCategoryId:"0",
            type:'topic',
            size:4,
            from:0
    }
        var res = await Data.getDocsBykeywords(q);
        var category ={
            value:"Other Topic",
            score:"0",

        }
        if(res.code==0){
            category.list = res.data.list
            list.push(category);
        }  

        return list;

 }

 

    
    

}